package com.xh.baselibrary.utils

import android.content.Context
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * GW00239435    2022/3/31
 */
class FileUtils {
    private fun doWriteFileToDevice(context: Context, assetsPath: String, destParentPath: String) {
        try {
            val files = context.assets.list(assetsPath)
            if (files != null && files.isNotEmpty()) {
                //文件夹
                val parentPath = destParentPath + File.separator + assetsPath
                val destParentFile = File(parentPath)
                if (!destParentFile.exists()) destParentFile.mkdirs()
                for (file in files) {
                    doWriteFileToDevice(context, assetsPath + File.separator + file, destParentPath)
                }
            } else {
                //文件
                val destParentFile = File(destParentPath + File.separator + assetsPath)
                if (destParentFile.exists()) {
                    return
                }
                val inputStream = context.assets.open(assetsPath)
                val buff = ByteArray(2048)
                val outputStream = FileOutputStream(destParentFile)
                var len = 0
                while (inputStream.read(buff).also { len = it } != -1) {
                    outputStream.write(buff, 0, len)
                }
                outputStream.flush()
                inputStream.close()
                outputStream.close()
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}